/**
 * 这是一个路由保护组件
 * 是保护那些需要用户登录才能访问的路由或组件。如果用户未登录，它通常会重定向用户到登录页面或显示一个错误消息。
 */
// RequireAuth.js
import React, { useState, useEffect } from "react";
import { Link, useLocation, useNavigate  } from "react-router-dom";
import {
  Box,
  Dialog,
  DialogActions,
  DialogTitle,
  Button,
  Paper,
} from "@mui/material";
import { isAuthenticated } from "./utilities";

// 高阶组件
function RequireAuth({ children }) {
  const [openDialog, setOpenDialog] = useState(false);
  const location = useLocation(); // 跟踪当前页面位置
  const navigate = useNavigate();
  useEffect(() => {
    // 组件加载时检查用户是否登录
    if (!isAuthenticated()) {
      setOpenDialog(true); // 如果用户未登录，打开对话框
    }
  }, [location.key]); // 依赖于location.key，当页面加载或路由变化时重新运行

  const handleCloseDialog = () => {
    setOpenDialog(false);
    navigate("/");
    
  };
  const closeDialog = (e, reason) => {
    if (reason === "escapeKeyDown" || reason === "backdropClick") {
      setOpenDialog(false);
    }
  };
  if (!isAuthenticated()) {
    return (
      <Box>
        {/*是否登录对话框 */}
        <Dialog open={openDialog} onClose={closeDialog}>
          <DialogTitle
            align="center"
            sx={{
              width: "200px",
            }}
          >
            游客无法访问该页面，是否进行登录
          </DialogTitle>
          <DialogActions
            sx={{
              display: "flex",
              flexFlow: "row nowrap",
              justifyContent: "space-around",
              height: 60,
            }}
          >
            <Button onClick={handleCloseDialog}>取消</Button>
            <Button component={Link} to={"/login"} autoFocus>
              确认
            </Button>
          </DialogActions>
        </Dialog>
      </Box>
    );
  }

  return <Box>{children}</Box>; // 用户已登录，渲染子组件
}

export default RequireAuth;
